﻿using System;
using System.Net;
using Newtonsoft.Json;
using tumblr.Api.Model;

namespace tumblr.Api
{
    public class Blog
    {
        public void GetPosts(string hostname, Action<Response> postsLoaded)
        {
            var request = new Uri(string.Format("http://api.tumblr.com/v2/blog/{0}/posts?api_key={1}&filter=text&notes_info=false", hostname, "2vM0AR3MJ5XCtPKWW1JIH32csLJ5w7lQSxRkYuNkQT49Qpckd6"));

            var webClient = new WebClient();
            webClient.DownloadStringCompleted += (sender ,e) => webClient_DownloadStringCompleted(e, postsLoaded);
            webClient.DownloadStringAsync(request);
        }

        private void webClient_DownloadStringCompleted(DownloadStringCompletedEventArgs e, Action<Response> postsLoaded)
        {
            if (e.Error != null)
                return;

            var result = JsonConvert.DeserializeObject<RootObject>(e.Result);

            postsLoaded(result.response);
        }
    }
}